package diva.pap.transactions;

import static diva.lib.lang.Lang.exception;
import static diva.lib.lang.Lang.is;

import android.view.View;
import diva.android_library.view.ViewBase;
import diva.lib.event.Event.EventRegistration;
import diva.lib.event.Task;
import diva.pap.R;
import diva.pap.TransactionsRequest;

public class TransactionRowBase extends ViewBase implements TransactionRow {

  protected TransactionsRequest request;
  private EventRegistration requestForRowLoadRegistration;
  protected int position;

  public void initialize(View view) {
    setView(view);
  }

  public void load(int position, TransactionsRequest request) {
    this.position = position;
    if (is(requestForRowLoadRegistration)) {
      requestForRowLoadRegistration.cancel();
      requestForRowLoadRegistration = null;
    }
    this.request = request;
    if (request.isDone())
      load();
    else {
      setWaiting(true);
      requestForRowLoadRegistration = request.eventLoaded().attach(new Task() {
        public void run() {
          load();
        }
      });
    }
  }

  protected int getStatusImage(CharSequence status) {
    if (status.equals("A")) return R.drawable.ic_transaction_approved;
    if (status.equals("D")) return R.drawable.ic_transaction_declined;
    if (status.equals("P")) return R.drawable.ic_transaction_pending;
    if (status.equals("R")) return R.drawable.ic_transaction_refund;
    throw exception();
  }

  protected void load() {
    setWaiting(false);
  }

  private void setWaiting(boolean waiting) {
    View bar = findViewById(R.id.transaction_row_progressbar);
    View data = findViewById(R.id.transaction_row_data);
    if (waiting) {
      bar.setVisibility(View.VISIBLE);
      data.setVisibility(View.GONE);
    } else {
      bar.setVisibility(View.GONE);
      data.setVisibility(View.VISIBLE);
    }
  }
}
